using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using twistmachinev2.CommonUse;

namespace twistmachinev2
{
    /// <summary>
    /// 现代化日志查看器窗口
    /// 支持日志文件浏览、日期搜索和内容查看
    /// </summary>
    public partial class FrmLogViewer : Form
    {
        private readonly string logDirectory;
        private List<FileInfo> logFiles;
        private Timer refreshTimer;

        public FrmLogViewer()
        {
            InitializeComponent();
            logDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
            InitializeForm();
            LoadLogFiles();
            SetupAutoRefresh();
        }

        private void InitializeForm()
        {
            // 设置窗口属性
            this.Text = "日志查看";
            this.Size = new Size(1200, 800);
            this.MinimumSize = new Size(800, 600);
            this.StartPosition = FormStartPosition.CenterScreen;
            this.BackColor = Color.FromArgb(240, 240, 240);
            this.Font = new Font("Microsoft YaHei UI", 9F);

            // 设置图标（如果有的话）
            try
            {
                this.Icon = SystemIcons.Information;
            }
            catch { }
        }

        private void LoadLogFiles()
        {
            try
            {
                if (!Directory.Exists(logDirectory))
                {
                    Directory.CreateDirectory(logDirectory);
                    return;
                }

                // 获取所有日志文件
                var files = Directory.GetFiles(logDirectory, "*.log", SearchOption.TopDirectoryOnly)
                    .Select(f => new FileInfo(f))
                    .OrderByDescending(f => f.LastWriteTime)
                    .ToList();

                logFiles = files;
                RefreshFileList();
            }
            catch (Exception ex)
            {
                LogManager.LogError($"加载日志文件失败: {ex.Message}");
                MessageBox.Show($"加载日志文件失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void RefreshFileList()
        {
            lstLogFiles.Items.Clear();

            var filteredFiles = logFiles;

            // 应用日期过滤
            if (dtpStartDate.Checked && dtpEndDate.Checked)
            {
                var startDate = dtpStartDate.Value.Date;
                var endDate = dtpEndDate.Value.Date.AddDays(1).AddSeconds(-1);

                filteredFiles = logFiles.Where(f => f.LastWriteTime >= startDate && f.LastWriteTime <= endDate).ToList();
            }

            // 应用文件名过滤
            if (!string.IsNullOrWhiteSpace(txtFileFilter.Text))
            {
                var filter = txtFileFilter.Text.ToLower();
                filteredFiles = filteredFiles.Where(f => f.Name.ToLower().Contains(filter)).ToList();
            }

            foreach (var file in filteredFiles)
            {
                var item = new ListViewItem(file.Name)
                {
                    Tag = file,
                    SubItems = {
                        file.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"),
                        FormatFileSize(file.Length)
                    }
                };

                // 根据文件类型设置不同颜色
                if (file.Name.Contains("Error"))
                {
                    item.ForeColor = Color.Red;
                }
                else if (file.Name.Contains("OpcUA"))
                {
                    item.ForeColor = Color.Blue;
                }
                else
                {
                    item.ForeColor = Color.Black;
                }

                lstLogFiles.Items.Add(item);
            }

            // 更新状态栏
            lblStatus.Text = $"共找到 {filteredFiles.Count} 个日志文件";
        }

        private string FormatFileSize(long bytes)
        {
            if (bytes < 1024) return $"{bytes} B";
            if (bytes < 1024 * 1024) return $"{bytes / 1024:F1} KB";
            if (bytes < 1024 * 1024 * 1024) return $"{bytes / (1024 * 1024):F1} MB";
            return $"{bytes / (1024 * 1024 * 1024):F1} GB";
        }

        private void LoadLogContent(FileInfo logFile)
        {
            try
            {
                txtLogContent.Clear();
                lblCurrentFile.Text = $"当前文件: {logFile.Name}";

                // 使用StreamReader读取文件，避免文件被占用的问题
                using (var stream = new FileStream(logFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                using (var reader = new StreamReader(stream, Encoding.UTF8))
                {
                    var content = reader.ReadToEnd();
                    txtLogContent.Text = content;

                    // 滚动到底部显示最新日志
                    txtLogContent.SelectionStart = txtLogContent.Text.Length;
                    txtLogContent.ScrollToCaret();
                }

                // 应用搜索高亮
                if (!string.IsNullOrWhiteSpace(txtSearch.Text))
                {
                    HighlightSearchText(txtSearch.Text);
                }
            }
            catch (Exception ex)
            {
                LogManager.LogError($"读取日志文件失败: {ex.Message}");
                txtLogContent.Text = $"读取文件失败: {ex.Message}";
                lblCurrentFile.Text = "当前文件: 无";
            }
        }

        private void HighlightSearchText(string searchText)
        {
            if (string.IsNullOrWhiteSpace(searchText)) return;

            txtLogContent.SelectAll();
            txtLogContent.SelectionBackColor = Color.White;
            txtLogContent.DeselectAll();

            int index = 0;
            while ((index = txtLogContent.Text.IndexOf(searchText, index, StringComparison.OrdinalIgnoreCase)) != -1)
            {
                txtLogContent.Select(index, searchText.Length);
                txtLogContent.SelectionBackColor = Color.Yellow;
                index += searchText.Length;
            }

            txtLogContent.DeselectAll();
        }

        private void SetupAutoRefresh()
        {
            refreshTimer = new Timer
            {
                Interval = 5000 // 5秒刷新一次
            };
            refreshTimer.Tick += (s, e) =>
            {
                if (chkAutoRefresh.Checked)
                {
                    LoadLogFiles();
                }
            };
            refreshTimer.Start();
        }

        private void ExportSelectedLogs()
        {
            if (lstLogFiles.SelectedItems.Count == 0)
            {
                MessageBox.Show("请先选择要导出的日志文件", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            using (var dialog = new SaveFileDialog())
            {
                dialog.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*";
                dialog.FileName = $"日志导出_{DateTime.Now:yyyyMMdd_HHmmss}.txt";

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        using (var writer = new StreamWriter(dialog.FileName, false, Encoding.UTF8))
                        {
                            foreach (ListViewItem item in lstLogFiles.SelectedItems)
                            {
                                var file = (FileInfo)item.Tag;
                                writer.WriteLine($"=== {file.Name} ===");
                                writer.WriteLine($"文件时间: {file.LastWriteTime}");
                                writer.WriteLine($"文件大小: {FormatFileSize(file.Length)}");
                                writer.WriteLine();

                                using (var stream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                                using (var reader = new StreamReader(stream, Encoding.UTF8))
                                {
                                    writer.WriteLine(reader.ReadToEnd());
                                }

                                writer.WriteLine();
                                writer.WriteLine(new string('=', 50));
                                writer.WriteLine();
                            }
                        }

                        MessageBox.Show("日志导出成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception ex)
                    {
                        LogManager.LogError($"导出日志失败: {ex.Message}");
                        MessageBox.Show($"导出失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        private void ClearOldLogs()
        {
            var result = MessageBox.Show(
                "确定要清理30天前的日志文件吗？\n此操作不可恢复！",
                "确认清理",
                MessageBoxButtons.YesNo,
                MessageBoxIcon.Warning);

            if (result == DialogResult.Yes)
            {
                try
                {
                    var cutoffDate = DateTime.Now.AddDays(-30);
                    var oldFiles = logFiles.Where(f => f.LastWriteTime < cutoffDate).ToList();

                    foreach (var file in oldFiles)
                    {
                        file.Delete();
                    }

                    LoadLogFiles();
                    MessageBox.Show($"已清理 {oldFiles.Count} 个旧日志文件", "清理完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    LogManager.LogError($"清理日志失败: {ex.Message}");
                    MessageBox.Show($"清理失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            refreshTimer?.Stop();
            refreshTimer?.Dispose();
            base.OnFormClosed(e);
        }

        #region 事件处理方法

        private void lstLogFiles_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstLogFiles.SelectedItems.Count > 0)
            {
                var selectedFile = (FileInfo)lstLogFiles.SelectedItems[0].Tag;
                LoadLogContent(selectedFile);
            }
        }

        private void dtpStartDate_ValueChanged(object sender, EventArgs e)
        {
            RefreshFileList();
        }

        private void dtpEndDate_ValueChanged(object sender, EventArgs e)
        {
            RefreshFileList();
        }

        private void txtFileFilter_TextChanged(object sender, EventArgs e)
        {
            RefreshFileList();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadLogFiles();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            ExportSelectedLogs();
        }

        private void btnClearLogs_Click(object sender, EventArgs e)
        {
            ClearOldLogs();
        }

        private void txtSearch_TextChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(txtLogContent.Text) && txtLogContent.Text != "请选择左侧的日志文件查看内容...")
            {
                // 实时搜索功能可以在这里实现，暂时注释掉以避免性能问题
                // HighlightSearchText(txtSearch.Text);
            }
        }

        private void txtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                e.SuppressKeyPress = true;
                SearchNext();
            }
            else if (e.KeyCode == Keys.F3)
            {
                e.SuppressKeyPress = true;
                if (e.Shift)
                    SearchPrevious();
                else
                    SearchNext();
            }
        }

        private void btnSearchNext_Click(object sender, EventArgs e)
        {
            SearchNext();
        }

        private void btnSearchPrev_Click(object sender, EventArgs e)
        {
            SearchPrevious();
        }

        #endregion

        #region 搜索功能

        private int currentSearchIndex = -1;
        private string lastSearchText = "";

        private void SearchNext()
        {
            if (string.IsNullOrWhiteSpace(txtSearch.Text)) return;

            var searchText = txtSearch.Text;
            if (searchText != lastSearchText)
            {
                currentSearchIndex = -1;
                lastSearchText = searchText;
            }

            var startIndex = currentSearchIndex + 1;
            if (startIndex >= txtLogContent.Text.Length)
                startIndex = 0;

            var index = txtLogContent.Text.IndexOf(searchText, startIndex, StringComparison.OrdinalIgnoreCase);
            if (index == -1 && startIndex > 0)
            {
                // 从头开始搜索
                index = txtLogContent.Text.IndexOf(searchText, 0, StringComparison.OrdinalIgnoreCase);
            }

            if (index != -1)
            {
                currentSearchIndex = index;
                txtLogContent.Select(index, searchText.Length);
                txtLogContent.ScrollToCaret();
                txtLogContent.Focus();
            }
            else
            {
                MessageBox.Show("未找到匹配的文本", "搜索结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void SearchPrevious()
        {
            if (string.IsNullOrWhiteSpace(txtSearch.Text)) return;

            var searchText = txtSearch.Text;
            if (searchText != lastSearchText)
            {
                currentSearchIndex = txtLogContent.Text.Length;
                lastSearchText = searchText;
            }

            var startIndex = currentSearchIndex - 1;
            if (startIndex < 0)
                startIndex = txtLogContent.Text.Length - 1;

            var index = txtLogContent.Text.LastIndexOf(searchText, startIndex, StringComparison.OrdinalIgnoreCase);
            if (index == -1 && startIndex < txtLogContent.Text.Length - 1)
            {
                // 从末尾开始搜索
                index = txtLogContent.Text.LastIndexOf(searchText, StringComparison.OrdinalIgnoreCase);
            }

            if (index != -1)
            {
                currentSearchIndex = index;
                txtLogContent.Select(index, searchText.Length);
                txtLogContent.ScrollToCaret();
                txtLogContent.Focus();
            }
            else
            {
                MessageBox.Show("未找到匹配的文本", "搜索结果", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        #endregion
    }
}